package com.adan.glmproduct.service.impl;

import com.adan.common.utils.PageUtils;
import com.adan.common.utils.Query;
import com.adan.glmproduct.dao.CategoryDao;
import com.adan.glmproduct.entity.CategoryEntity;
import com.adan.glmproduct.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类。baseMapper来自于继承的ServiceImpl<>类，跟CategoryDao一样用法
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2、递归组装多级分类的树形结构。先过滤(筛选出一级菜单，也就是ParentCid=0)得到一级分类，再加工递归设置一级分类的子孙分类，再排序，再收集
        List<CategoryEntity> level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    // 设置一级分类的子分类
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .sorted(
                        //排序，sort是实体类的排序属性，值越小优先级越高，要判断非空防止空指针异常
                        // 方法一：
                        // return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                        // 方法二：
                        Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))
                        // 方法三： 整体升序，price为null的排在最前
                        // Comparator.comparing(CategoryEntity::getSort, Comparator.nullsFirst(Comparator.naturalOrder()))
                ).collect(Collectors.toList());

        return level1Menus;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
        // 筛选出子菜单，当子菜单的ParentCid等于父id
        return all.stream().filter(item -> item.getParentCid().equals(root.getCatId()))
                .map(item -> {
                    item.setChildren(getChildren(item, all));
                    return item;
                }).sorted(Comparator.comparingInt(item -> item.getSort() == null ? 0 : item.getSort()))
                .collect(Collectors.toList());
    }

}